/*
 * Copyright (C), 2002-2016, 上海亦寻信息技术有限公司
 * FileName: PayDepositServiceImpl.java
 * Author:   linyao
 * Date:     2016-6-27 下午5:29:15
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.website.service.payDeposit;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.vo.process.HistoryTaskInfoVo;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class PayDepositServiceImp implements PayDepositService {

	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private TaskService taskService;
	
	 @Autowired
	 private UserServiceFacade userServiceFacade;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.website.service.payDeposit.PayDepositService#getPayDepositList(com.emm.yixun.common.model.dto.
	 * PayDepositDto, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<Page<PayDepositDto>> getPayDepositList(PayDepositDto reqDto, Integer pageSize, Integer pageNum) {
		if (StringUtils.isNotBlank(reqDto.getM_auditStatus())) {
			String sql = new String(" and t.audit_status in (");
			String[] audits = reqDto.getM_auditStatus().split(",");
			String sbsql = "";
			for (int i = 0; i < audits.length; i++) {
				sbsql += audits[i];
				if (i != audits.length - 1) {
					sbsql += ",";
				}
			}
			sql += sbsql + ")";
			reqDto.setM_auditStatus(sql);
		}
		if (StringUtils.isNotBlank(reqDto.getM_businessStatus())) {
			String sql = new String(" and t.business_status in (");
			String[] status = reqDto.getM_businessStatus().split(",");
			String sbsql = "";
			for (int i = 0; i < status.length; i++) {
				sbsql += status[i];
				if (i != status.length - 1) {
					sbsql += ",";
				}
			}
			sql += sbsql + ")";
			reqDto.setM_businessStatus(sql);
		}

		Response<Page<PayDepositDto>> depositListResDto = payDepositServiceFacade.getPayDepositList(reqDto, pageSize,
				pageNum);

		if (reqDto.getCustomerId() != null && depositListResDto.isSuccess() && depositListResDto.getEntity() != null
				&& depositListResDto.getEntity().getRows() != null
				&& depositListResDto.getEntity().getRows().size() > 0) {// 查询审批历史记录
			List<PayDepositDto> list = depositListResDto.getEntity().getRows();
			for (PayDepositDto payDepositDto : list) {
				if (payDepositDto.getProcInstId() != null) {
					List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery()
							.processInstanceId(payDepositDto.getProcInstId())
							.orderByHistoricActivityInstanceStartTime().desc().list();
					if (instances != null && instances.size() > 0) {
						boolean isEnd = true;
						List<HistoryTaskInfoVo> userTaskList = new ArrayList<HistoryTaskInfoVo>();
						for (HistoricActivityInstance historicActivityInstance : instances) {
							if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
								HistoryTaskInfoVo htf = new HistoryTaskInfoVo();

								if (historicActivityInstance.getActivityType().equals("startEvent")) {// 开始节点
									ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
											.createProcessInstanceHistoryLogQuery(
													historicActivityInstance.getProcessInstanceId()).singleResult();
									htf.setTaskName("启动");
									UserDto ud=new UserDto();
									ud.setUserAccount(processInstanceHistoryLog.getStartUserId());
									ResponseList<User> userList=userServiceFacade.findByDto(ud);
									if(userList.isSuccess() && null!=userList.getEntity()){
										htf.setTaskUserName(userList.getEntity().get(0).getUserName());
									}
									htf.setTaskCheckStatus("发起");
									htf.setStartDate(historicActivityInstance.getStartTime());
									htf.setEndDate(historicActivityInstance.getEndTime());

									userTaskList.add(htf);
									continue;
								}

								if (historicActivityInstance.getActivityType().equals("endEvent")) {// 结束节点
									continue;
								}

								List<Comment> commentList = taskService.getTaskComments(historicActivityInstance
										.getTaskId());
								htf.setTaskName(historicActivityInstance.getActivityName());
								htf.setStartDate(historicActivityInstance.getStartTime());
								htf.setEndDate(historicActivityInstance.getEndTime());
								if (isEnd)// 为最后一个审批节点
									htf.setIsEnd(isEnd);
								if (null != commentList && commentList.size() > 0){
									String userAccount=commentList.get(0).getUserId();
									UserDto ud=new UserDto();
									ud.setUserAccount(userAccount);
									ResponseList<User> userList=userServiceFacade.findByDto(ud);
									if(userList.isSuccess() && null!=userList.getEntity()){
										htf.setTaskUserName(userList.getEntity().get(0).getUserName());
									}
									
								}

								userTaskList.add(htf);
								isEnd = false;
							}
						}

						if (userTaskList.size() > 0) {
							for (HistoryTaskInfoVo historyTaskInfoVo : userTaskList) {
								if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
									payDepositDto.setSmTartTime(historyTaskInfoVo.getStartDate());
								}
								if (historyTaskInfoVo.getIsEnd() != null && historyTaskInfoVo.getIsEnd()) {// 获取最后的审批人与审核时间
									payDepositDto.setTaskUserName(historyTaskInfoVo.getTaskUserName());
									payDepositDto.setCkEndTime(historyTaskInfoVo.getEndDate());
								}
							}
						}
					}
				}

			}

		}

		return depositListResDto;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.website.service.payDeposit.PayDepositService#selectPayDepositCustomer(java.lang.Long)
	 */
	@Override
	public Response<PayDepositDto> selectPayDepositCustomer(Long id) {
		return payDepositServiceFacade.selectPayDepositCustomer(id);
	}
}
